<?php
// @formatter:off
/**
 * @file c.edit.TAGGER-MOVE.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-06-04 03:02:53 +0000 (Tue, 04 Jun 2013) $
 *
 * $Id: c.edit.TAGGER-MOVE.php 68 2013-06-04 03:02:53Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0.0.1/extensions/DirectoryOrganizer/controlers/c.edit.TAGGER-MOVE.php $
 */
// @formatter:on

global $wcDirectoriesHolder;
global $wcTagsHolder;

switch($_POST["EDITACTION"]) {
	case "SET":
		if(isset($_POST["ACTION_DIRECTORY"]) && isset($_POST["ACTION_TAGS"])) {
			$diretoryName = explode(",", $_POST["ACTION_DIRECTORY"]);

			$newTagNames = array();
			foreach(explode(",",$_POST["ACTION_TAGS"]) as $tagName) {
				$tagName = trim($tagName);
				if($tagName) {
					$newTagNames[] = $tagName;
				}
			}
			if(count($diretoryName) > 0 && count($newTagNames) > 0) {
				$diretoryName = array_shift($diretoryName);
				$directory = $wcDirectoriesHolder->itemByName($diretoryName, $wcGroup);

				$newTags = array();
				foreach($newTagNames as $name) {
					$tag = $wcTagsHolder->itemByName($name, $wcGroup);
					//
					// If it is a new tag it creates it.
					if(!$tag) {
						$wcTagsHolder->create($name, $wcGroup);
						$tag = $wcTagsHolder->itemByName($name, $wcGroup);
					}

					if($tag && $tag->ok()) {
						$newTags[$tag->id] = $tag;
					}
				}

				$stmt = null;
				$stmtId = __CLASS__."::".__FUNCTION__."[TAGGER-CLEANN]";
				if($db->has($stmtId)) {
					$stmt = $db->get($stmtId);
				} else {
					$query = "delete from {$dbprefix}acts_dor\n";
					$query .= "where      act_rule   = :rule\n";
					$query .= " and       act_group  = :group\n";
					$query .= " and       act_action = :action\n";

					$stmt = $db->prepare($stmtId, $query);
				}
				$params = array(
					":rule" => $wcRule->id(),
					":group" => $wcGroup->id,
					":action" => $wcRuleAction->id()
				);
				$stmt->execute($params);

				$stmt = null;
				$stmtId = __CLASS__."::".__FUNCTION__."[TAGGER-SET]";
				if($db->has($stmtId)) {
					$stmt = $db->get($stmtId);
				} else {
					$query = "insert\n";
					$query .= "        into {$dbprefix}acts_dor (\n";
					$query .= "                act_rule, act_group, act_action, act_tag, act_directory, act_user)\n";
					$query .= "        values (:rule, :group, :action, :tag, :directory, :user)\n";

					$stmt = $db->prepare($stmtId, $query);
				}

				if($directory && $directory->ok()) {
					foreach($newTags as $tag) {
						$params = array(
							":rule" => $wcRule->id(),
							":group" => $wcGroup->id,
							":action" => $wcRuleAction->id(),
							":tag" => $tag->id,
							":directory" => $directory->id,
							":user" => $wcUser->id
						);
						$stmt->execute($params);
					}
				}
				$wcRuleAction->reload();
			}
		}

		break;
	default:
		break;
}
?>